package org.example.onlinechat.controller;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import jakarta.servlet.http.HttpSession;
import org.example.onlinechat.common.Result;
import org.example.onlinechat.entity.OrdMsg;
import org.example.onlinechat.entity.SystemData;
import org.example.onlinechat.entity.User;
import org.example.onlinechat.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

@CrossOrigin(origins = "http://localhost:7070")
@RestController
@RequestMapping("/applications")
public class ChatController {
    @Autowired
    private ChatService chatService;

//    @RequestMapping("/c1")//建立连接
//        public Result Chat(@RequestBody User user, HttpSession session) throws JsonProcessingException {
//        String content =user.getContent();
//        System.out.println(content);
//        SystemData systemData = new SystemData();
//        ArkService service =chatService.ChatSer();
//        List<ChatMessage> messages = new ArrayList<>();
//        List<ChatMessage> list= (List<ChatMessage>) session.getAttribute("systemData");
//        System.out.println(list);
//        if (session.getAttribute("systemState")!=null){
//            if (session.getAttribute("systemState").equals("true")){
//                String data = chatService.selectData(user.getUser_id());
//                if(data!=null){
//                    ObjectMapper objectMapper = new ObjectMapper();
//                    List<ChatMessage> list1 = objectMapper.readValue(data, TypeFactory.defaultInstance().constructCollectionType(List.class, ChatMessage.class));
//                    messages.addAll(list1);
//                    session.setAttribute("systemData","false");
//                }
//            }
//        }
//        if (list!=null){
//            messages=list;
//        }
//        if (content.equals("exit")||content.equals("quit")){
//            session.invalidate();
//            System.exit(0);
//        }
//        if (list==null||list.size()==0){
//            ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("你是豆包，是由字节跳动开发的 AI 人工智能助手,现在扮演一名资深的情感咨询师").build();
//            messages.add(systemMessage);
//        }
//            ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(content).build();
//            messages.add(userMessage);
//            ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
//                    .model(systemData.getRequestKey())
//                    .messages(messages)
//                    .build();
//
//            String responseContent = (String) service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage().getContent();
//            try {
//                // 获取响应并打印回复内容
//                System.out.println("豆包：" + responseContent);
//                // 将回复添加到消息列表，以便下一轮对话参考
//                ChatMessage assistantMessage = ChatMessage.builder().role(ChatMessageRole.ASSISTANT).content(responseContent).build();
//                messages.add(assistantMessage);
//                systemData.setMsgData(messages);
//                service.shutdownExecutor();
//
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        List<ChatMessage> list1= systemData.getMsgData();
//        ObjectMapper objectMapper = new ObjectMapper();
//        // 将对象转换为 JSON 字符串
//        String json = objectMapper.writeValueAsString(list1);
//        chatService.insertChatMessage(String.valueOf(user.getUser_id()),json);
//           session.setAttribute("systemData", systemData.getMsgData());
//           return Result.success(messages);
//    }

    @RequestMapping("/chat")
    public Result Chat_1(@RequestBody User user, HttpSession session) throws JsonProcessingException {
        String content =user.getContent();
        SystemData systemData = new SystemData();
        ArkService service =chatService.ChatSer();
        List<ChatMessage> messages = new ArrayList<>();
        String data = chatService.selectData(user.getUser_id());
        if (content.equals("exit")||content.equals("quit")){
            session.invalidate();
            System.exit(0);
        }
        if(data!=null) {//从数据库获取当前对话，并更新到list1
            ObjectMapper objectMapper = new ObjectMapper();
            List<ChatMessage> list1 = objectMapper.readValue(data, TypeFactory.defaultInstance().constructCollectionType(List.class, ChatMessage.class));
            messages.addAll(list1);
        }
        if (data==null){//如果当前对话为空，则重新对话
            ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("你是豆包，是由字节跳动开发的 AI 人工智能助手,现在扮演一名资深的情感咨询师").build();
            messages.add(systemMessage);//设置系统预设角色
        }
        ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(content).build();
        messages.add(userMessage);//将用户信息构成成user发送的信息，并加到请求中
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(systemData.getRequestKey())
                .messages(messages)
                .build();

        String responseContent = (String) service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage().getContent();
        try {
            // 获取响应并打印回复内容
//            System.out.println("豆包：" + responseContent);
            // 将回复添加到消息列表，以便下一轮对话参考
            ChatMessage assistantMessage = ChatMessage.builder().role(ChatMessageRole.ASSISTANT).content(responseContent).build();
            messages.add(assistantMessage);//将用户信息构成成机器人发送的信息，并加到请求中
            systemData.setMsgData(messages);
            service.shutdownExecutor();

        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ChatMessage> list1= systemData.getMsgData();
        ObjectMapper objectMapper = new ObjectMapper();
        // 将对象转换为 JSON 字符串
        String json = objectMapper.writeValueAsString(list1);
        chatService.insertChatMessage(String.valueOf(user.getUser_id()),json);
        return Result.success(messages);
    }

    @RequestMapping("/c2")//更新或新增用户聊天记录，
    public Result Chat(@RequestBody String user_id,HttpSession session) throws JsonProcessingException {
        List<ChatMessage> list= (List<ChatMessage>) session.getAttribute("systemData");
        ObjectMapper objectMapper = new ObjectMapper();
        // 将对象转换为 JSON 字符串
        String json = objectMapper.writeValueAsString(list);
        chatService.insertChatMessage(user_id,json);
        return Result.success();
    }

    @RequestMapping("/c3")//查询用户聊天记录
    public Result ChatSelect(@RequestParam int user_id) throws JsonProcessingException {
        String data = chatService.selectData(user_id);
        if(data!=null){
            ObjectMapper objectMapper = new ObjectMapper();
            List<ChatMessage> list1 = objectMapper.readValue(data, TypeFactory.defaultInstance().constructCollectionType(List.class, ChatMessage.class));
            return  Result.success(list1);
        }
        return Result.error();
    }


    @RequestMapping("/c4")//插入历史数据库
    public Result ChatCreate(@RequestParam int user_id,HttpSession session ){
        chatService.ChatCreate(user_id);
        session.invalidate();
        return Result.success();

    }


    @RequestMapping("/c5")//查询历史记录
    public Result chatSelectOrd(@RequestParam int user_id){
        List<OrdMsg> ordMsgs = chatService.selectOrdData(user_id);
        return Result.success(ordMsgs);
    }

    @RequestMapping("/c6")//查询历史记录
    public Result chatSelectOrdN(@RequestBody OrdMsg msg){
        return Result.success( chatService.chatSelectOrdN(msg));
    }

    @RequestMapping("/c7")//查询历史记录
    public Result ChatIn(@RequestBody User msg){
        chatService.insertChatMessage(String.valueOf(msg.getUser_id()),msg.getContent());
        return Result.success();
    }

    @RequestMapping("/c8")
    public Result ChatOut(){
        return Result.success(chatService.SALL());
    }

}
